package pe.com.itworth.ttsclient.infrastructure;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.InternetAddress;

import pe.com.itworth.ttsclient.shared.MailDTO;

import com.sun.mail.imap.IMAPFolder;

import net.htmlparser.jericho.Source;

public class MailReaderJavaMailImpl implements MailReader<Message> {

	@Override
	public MailDTO read(Message message) {
		MailDTO mail = new MailDTO();
		
		try {
			// Get the header information
			String sFrom = ((InternetAddress) message.getFrom()[0])
					.getPersonal();
			if (sFrom == null)
				sFrom = ((InternetAddress) message.getFrom()[0]).getAddress();

			mail.setsFrom(sFrom);

			String sSubject = message.getSubject();
			mail.setsSubject(sSubject);

			Date dSendDate = message.getSentDate();
			mail.setdDate(dSendDate);
			
			Integer iUid = (int)((IMAPFolder)message.getFolder()).getUID(message);
			mail.setiUid(iUid);

			// -- Get the message part (i.e. the message itself) --
			Part messagePart = message;
			Object content = messagePart.getContent();

			// -- or its first body part if it is a multipart message --
			if (content instanceof Multipart) {

				int iIndex = 0;
				messagePart = ((Multipart) content).getBodyPart(iIndex);
				System.out.println("[ Multipart Message ]");

				while (messagePart != null) {
					String sMsg = sReadBodyPart(messagePart);
					if (sMsg != null)
						mail.setsMessage(sMsg);

					iIndex++;
					try {
						messagePart = ((Multipart) content).getBodyPart(iIndex);
					} catch (Exception e) {
						messagePart = null;
					}
				}
				return mail;
			}

			String sMsg = sReadBodyPart(messagePart);
			mail.setsMessage(sMsg);
			//TAMBIEN FUNCIONA CON ESTO
			//mail.setMessage(message.getContent().toString());
			//PERO ESTO DE UN MOMENTO A OTRO CUANDO USE POP3 ME GENERO PROBLEMAS
			//MEJOR ME QUEDO CON EL OTRO...AUNQUE NO RECONOCE VOCALES TILDADAS

			return mail;
		} catch (Exception ex) {
			ex.printStackTrace();
			if(mail.getsFrom() == null)
				return null;
			
			return mail;
		}
	}

	private String sReadBodyPart(Part messagePart) {
		String sMsg = null;

		try {
			// -- Get the content type --
			String sContentType = messagePart.getContentType().toUpperCase();
			// -- If the content is plain text, we can print it --
			System.out.println("CONTENT:" + sContentType);

			if (sContentType.startsWith("TEXT/PLAIN")
					|| sContentType.startsWith("TEXT/HTML")) {
				InputStream is = messagePart.getInputStream();

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is));

				sMsg = "";
				String sThisLine = reader.readLine();

				while (sThisLine != null) {
					System.out.println(sThisLine);
					sMsg = sMsg + sThisLine + "\n";
					sThisLine = reader.readLine();
				}
				
				if(sContentType.startsWith("TEXT/HTML")) {
					Source source = new Source(sMsg);
					sMsg = source.getRenderer().toString();
				}
				
				
			}

		} catch (Exception e) {
			return null;
		}

		return sMsg;
	}

}
